package it.michaellinker.msr.web.util.metric.counter;

import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;

/**
 * Counter based on queue.
 *
 * @param <T> The type of object to count.
 */
public class QueueCounter<T> implements RequestCounter<T> {
    private final Queue<T> counterQueue;

    public QueueCounter() {
        counterQueue = new LinkedBlockingQueue<>();
    }

    @Override
    public void count(T key) {
        counterQueue.add(key);
    }

    @Override
    public synchronized Map<T, Long> getResult() {
        Map<T, Long> bufferCounterMap;
        bufferCounterMap = counterQueue.stream()
                .collect(Collectors.groupingBy(t -> t, Collectors.counting()));
        counterQueue.clear();
        return bufferCounterMap;
    }
}
